package com.wwwarehouse.usercenter.activity;

import android.os.Bundle;
import android.os.Handler;
import android.support.annotation.Nullable;
import android.text.Editable;
import android.text.Selection;
import android.text.Spannable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.text.method.HideReturnsTransformationMethod;
import android.text.method.PasswordTransformationMethod;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.TextView;

import com.wwwarehouse.common.activity.base.BaseActivity;
import com.wwwarehouse.common.bean.response.CommonClass;
import com.wwwarehouse.common.common.Common;
import com.wwwarehouse.common.custom_widget.ClearEditText;
import com.wwwarehouse.common.custom_widget.textinput.TextInputLayout;
import com.wwwarehouse.common.http.NoHttpUtils;
import com.wwwarehouse.common.tools.rsa.Base64Utils;
import com.wwwarehouse.common.tools.rsa.RSAUtil;
import com.wwwarehouse.usercenter.R;
import com.wwwarehouse.usercenter.constant.UserCenterConstant;

import java.util.HashMap;
import java.util.Map;

/**
 * Created by Jackie on 2017/6/27.
 * 忘记密码
 */

public class ForgetPasswordStep3Activity extends BaseActivity implements View.OnClickListener, TextWatcher, ClearEditText.onMyFocusChangeListener {
    private View mRootView;

    private ImageView mBackImg;
    private TextView mTitleTxt;

    private TextInputLayout mNewPasswordLayout;
    private ClearEditText mNewPasswordEdt;
    private TextInputLayout mAgainPasswordLayout;
    private ClearEditText mAgainPasswordEdt;

    private ImageView mEyeImg;

    private Button mSureBtn;

    private String mMobile;
    private String mSMSCode;

    private boolean mIsEyeOpened = false;

    private Handler mHandler = new Handler();

    //密码6-16位，由字母加数字组成
    private static final String REGEX  = "^(?![0-9]+$)(?![a-zA-Z]+$)[0-9A-Za-z]{6,16}$";

    private static final int REQUEST_UPDATE_PASSWORD = 0;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        setContentView(R.layout.activity_forget_password_3);

        Bundle bundle = getIntent().getExtras();
        if (bundle != null) {
            mMobile = bundle.getString(UserCenterConstant.KEY_LOGIN_MOBILE);
            mSMSCode = bundle.getString(UserCenterConstant.KEY_LOGIN_SMS_CODE);
        }

        initView();
        initEvent();
    }

    private void initView() {
        mRootView = findView(R.id.rl_root);

        mBackImg = findView(R.id.back_bt);
        mTitleTxt = findView(R.id.title_text);
        mTitleTxt.setText(R.string.set_new_password);

        mNewPasswordLayout = findView(R.id.til_new_password);
        mNewPasswordEdt = findView(R.id.et_new_password);
        mAgainPasswordLayout = findView(R.id.til_again_password);
        mAgainPasswordEdt = findView(R.id.et_again_password);

        mEyeImg = findView(R.id.iv_eye);

        mSureBtn = findView(R.id.btn_sure);
    }

    private void initEvent() {
        mRootView.setOnClickListener(this);

        mBackImg.setOnClickListener(this);

        mNewPasswordEdt.addTextChangedListener(this);
        mNewPasswordEdt.setOnMyFocusChangeListener(this);
        mNewPasswordEdt.setLongClickable(false);
        mNewPasswordEdt.setTextIsSelectable(false);
        mAgainPasswordEdt.addTextChangedListener(this);
        mAgainPasswordEdt.setOnMyFocusChangeListener(this);
        mAgainPasswordEdt.setLongClickable(false);
        mAgainPasswordEdt.setTextIsSelectable(false);

        mEyeImg.setOnClickListener(this);

        mSureBtn.setOnClickListener(this);
    }

    @Override
    public void onClick(View v) {
        int id = v.getId();

        if (id == R.id.rl_root) {
          hideSoftKeyBoard(mRootView);
        } else if (id == R.id.back_bt) {
            finishActivity();
        } else if (id == R.id.iv_eye) {
            if (!mIsEyeOpened) {
                mEyeImg.setImageResource(R.drawable.register_open_eyes);

                mNewPasswordEdt.setTransformationMethod(HideReturnsTransformationMethod.getInstance());
                mAgainPasswordEdt.setTransformationMethod(HideReturnsTransformationMethod.getInstance());
            } else {
                mEyeImg.setImageResource(R.drawable.register_close_eye);

                mNewPasswordEdt.setTransformationMethod(PasswordTransformationMethod.getInstance());
                mAgainPasswordEdt.setTransformationMethod(PasswordTransformationMethod.getInstance());
            }

            mNewPasswordEdt.postInvalidate();
            mAgainPasswordEdt.postInvalidate();

            mIsEyeOpened = !mIsEyeOpened;

            CharSequence newText = mNewPasswordEdt.getText();
            CharSequence againText = mAgainPasswordEdt.getText();
            if (newText instanceof Spannable) {
                Spannable newSpannable = (Spannable) newText;
                Selection.setSelection(newSpannable, newText.length());
            }

            if (againText instanceof Spannable) {
                Spannable againSpannable = (Spannable) againText;
                Selection.setSelection(againSpannable, againText.length());
            }
        } else if (id == R.id.btn_sure) {   //修改密码
            updatePassword();
        }
    }

    @Override
    public void beforeTextChanged(CharSequence s, int start, int count, int after) {

    }

    @Override
    public void onFocusChange(View view, boolean hasFocus) {
        if (view instanceof ClearEditText && hasFocus) {
            int id = view.getId();

            if (id == R.id.et_new_password) {
                //首先校验格式是否正确，然后校验密码是否一致
                checkNewPassword();
                checkAgainPassword();
            } else if (id == R.id.et_again_password) {
                //校验新密码新密码格式是否正确
                checkNewPassword();
            }
        }
    }

    @Override
    public void onTextChanged(CharSequence s, int start, int before, int count) {
        if (!TextUtils.isEmpty(mNewPasswordEdt.getText().toString().trim()) &&
                !TextUtils.isEmpty(mAgainPasswordEdt.getText().toString().trim())) {
            mSureBtn.setEnabled(true);
            mSureBtn.setBackgroundResource(R.drawable.common_btn2_solid_selector);
        } else {
            mSureBtn.setEnabled(false);
            mSureBtn.setBackgroundResource(R.drawable.common_btn1_noclick_shape);
        }
    }

    @Override
    public void afterTextChanged(Editable s) {

    }

    private boolean checkNewPassword() {
        String newPassword = mNewPasswordEdt.getText().toString().trim();

        if (!newPassword.matches(REGEX)) {
            mNewPasswordLayout.setStateWrong(getString(R.string.password_is_illegal));
            return false;
        } else {
            mNewPasswordLayout.setStateNormal();
            return true;
        }
    }

    private boolean checkAgainPassword() {
        String newPassword = mNewPasswordEdt.getText().toString().trim();
        String againPassword = mAgainPasswordEdt.getText().toString().trim();

        if (!TextUtils.equals(newPassword, againPassword)) {
            mNewPasswordLayout.setStateWrong(getString(R.string.twice_input_password_must_be_consistent));
            return false;
        } else {
            mNewPasswordLayout.setStateNormal();
            return true;
        }
    }

    private void updatePassword() {
        if (checkNewPassword() && checkAgainPassword()) {
            String newPassword = mNewPasswordEdt.getText().toString().trim();

            Map map = new HashMap();
            map.put("mobile", mMobile);
            try {
                byte[] data = RSAUtil.encryptByPublicKey(newPassword.getBytes(), RSAUtil.publicKey);
                newPassword = Base64Utils.encodeBase64(data);
                map.put("password", newPassword);
            } catch (Exception e) {
                e.printStackTrace();
            }

            map.put("verifyCode", mSMSCode);

            NoHttpUtils.httpPost(UserCenterConstant.URL_UPDATE_PASSWORD, map, mOnResponseListener, REQUEST_UPDATE_PASSWORD);
        }
    }

    NoHttpUtils.OnResponseListener mOnResponseListener = new NoHttpUtils.OnResponseListener() {
        @Override
        public void onSucceed(CommonClass commonClass, int what) {
            switch (what) {
                case REQUEST_UPDATE_PASSWORD:
                    if ("0".equals(commonClass.getCode())) {
                       //密码更新成功，跳转到登录页面重新登录
                        startActivity(LoginActivity.class, null, true);

                        mHandler.postDelayed(new Runnable() {
                            @Override
                            public void run() {
                                Common.getInstance().finishAllActivity();
                            }
                        }, 800);
                    } else {
                        toast(commonClass.getMsg());
                    }
                    break;
                default:
                    break;
            }
        }

        @Override
        public void onFailed(String result, int what) {
            toast(result);
        }

        @Override
        public void onFinish(int what) {

        }
    };
}
